import request from "@/utils/request";
import React, { useState, useCallback, useEffect } from "react";
import { Form,Table,DatePicker, Input, Button, Tag, Space, Modal, Badge,Select, message } from "antd";
import Highlighter from "react-highlight-words";
import { SearchOutlined } from "@ant-design/icons";
import moment from 'moment'
function Repair() {
  const [datalist, setDatalist] = useState([]);
  const [searchText, setSearchText] = useState("");
  const [searchedColumn, setSearchedColumn] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [details, setDetails] = useState("");
  const { Option } = Select;
  const { TextArea } = Input;
  const [id,setId]=useState('')
  const [state,setState]=useState('')

  

  // 数据列表
  const getData = useCallback(async function () {
    const { data } = await request.post("/repair/select", {
      page: 1,
      size: 25,
    });
    setDatalist(data.ret);
  }, []);
  useEffect(() => {
    getData();
  }, []);

  // const data = useCallback(async function () {
  //   const { data } = await request.post("/repair/addrepair", {
  //     data: {
  //       dormitory: "A1-343",
  //       endtime: "",
  //       id: 12154575,
  //       problem: "风扇不转了",
  //       remark: "",
  //       state: '2',
  //       statetime: "2021-6-26",
  //       username: "小福",
  //     },
  //   });
  //   console.log("data", data);
  //   getData();
  // }, []);

  // 按条件查询
  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            setSearchInput(node);
          }}
          placeholder={`搜索 ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            清空
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : "",
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        // setTimeout(() =>searchInput.select(), 100)}
        // console.log(1);
      }
    },
    render: (text) =>
      searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
          searchWords={[searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText("");
  };

  let list = datalist.map((value) => {
    value["key"] = value._id;
    return value;
  });

  const columns = [
    {
      title: "单号",
      dataIndex: "id",
      width: "12%",
      ...getColumnSearchProps("单号"),
    },
    {
      title: "姓名",
      width: "10%",
      dataIndex: "username",
      ...getColumnSearchProps("姓名"),
    },
    {
      title: "问题",
      width: "12%",
      dataIndex: "problem",
      ...getColumnSearchProps("问题"),
    },
    {
      title: "宿舍",
      width: "10%",
      dataIndex: "dormitory",
      ...getColumnSearchProps("宿舍"),
    },
    {
      title: "状态",
      dataIndex: "state",
      width: "8%",
      ...getColumnSearchProps("状态"),
      render: (_,record) => {
        if(record.state==='1'){
          return <Tag color="success">完成</Tag>
        }
        else if(record.state==='2'){
          return <Tag color="error">未完成</Tag>
        }else if(record.state==='0'){
          return <Tag color="error">已驳回</Tag>
        }
      }
    },
    {
      title: "提交时间",
      dataIndex: "statetime",
      width: "10%",
      ...getColumnSearchProps("提交时间"),
    },
    {
      title: "完成时间",
      dataIndex: "endtime",
      width: "10%",
      ...getColumnSearchProps("完成时间"),
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: "12%",
      ...getColumnSearchProps("备注"),
    },
    {
      title: "操作",
      key: "操作",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            onClick={() => {
              showDetails(record.key);
            }}
          >
            查看
          </Button>
          <Button
            type="danger"
            size="small"
            onClick={() => {
              showState(record.key);
            }}
          >
            修改状态
          </Button>
        </Space>
      ),
    },
  ];

  // 查看详情
  const showDetails = (key) => {
    console.log(key);
    setIsModalVisible(true);
    const newData = [...list];
    const index = newData.findIndex((item) => key === item.key);
    if (index > -1) {
      const item = newData[index];
      setDetails(item);
    }
  };

  // 状态修改 0:未完成，1：完成，2：驳回
  const showState=(key)=>{
    setState(true);
    const newData = [...list];
    const index = newData.findIndex((item) => key === item.key);
    if (index > -1) {
      const item = newData[index];
      setDetails(item);
      setId(item.id)
      console.log(item);
    }
  }
  const ModifyItem = () => {

    const onFinish = useCallback(async function (values) {
      values.endtime = moment(values.endtime).format('YYYY-MM-DD');
     const time= values.endtime==='Invalid date'?'':values.endtime
     const { data } = await request.put("/repair/updatarepair", {
      id:id,
      data: { 
        endtime: time,
        remark: values.remark,
        state: values.state,
      },
    })
    if(data.code===200){
      getData()
      message.success('修改状态成功！')
    }else{
      message.error('修改状态失败！')
    }

    })
    const onFinishFailed = (errorInfo) => {
      console.log("Failed:", errorInfo);
    };
  
      return (
        <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 16,
        }}
        initialValues={{
          state:'2',
          endtime:'',
          remark:''
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
        name="time_related_controls" 
      >
        <Form.Item
          name="state"
          label="状态"
        >
        <Select
          placeholder="请选择"
        >
          <Option value='0'>驳回</Option>
          <Option value='1'>完成</Option>
          <Option value='2'>未完成</Option>
        </Select>
        </Form.Item>
        <Form.Item name="endtime" label="完成时间：" >
          <DatePicker placeholder="请选择" initialValues={moment(null)}/>
        </Form.Item>
        <Form.Item
          label="备注"
          name="remark"
        >
          <TextArea showCount maxLength={80} style={{width:'300px',display:'inline-block',marginTop:'20px'}}/>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            offset: 10,
            span: 16,
          }}
        >
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
        </Form>
      );
  }

  const handleCancel = () => {
    setIsModalVisible(false);
    setState(false)
  };

  
  return (
    <div>
      {/* <Button
        size="small"
        style={{ background: "#58bc58", color: "white" }}
        onClick={data}
      >
        添加
      </Button> */}
      <Table columns={columns} dataSource={list} />
      <Modal
        title="详细信息"
        visible={isModalVisible}
        footer={null}
        onCancel={handleCancel}
        style={{ height: "400px", width: "400px" }}
      >
        <div>
          <p id="repairP">
            <span id="repairSpan">单号:</span>
            <span>{details.id}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">姓名:</span>
            <span>{details.username}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">问题:</span>
            <span>{details.problem}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">宿舍:</span>
            <span>{details.dormitory}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">状态:</span>
            <span>{details.state === "2" ? "未完成" : "完成"}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">提交时间:</span>
            <span>{details.statetime}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">完成时间:</span>
            <span>{details.endtime}</span>
          </p>
          <p id="repairP">
            <span id="repairSpan">备注:</span>
            <span>{details.remark}</span>
          </p>
        </div>
      </Modal>
      <Modal
        title="修改完成状态"
        visible={state}
        footer={null}
        onCancel={handleCancel}
        style={{ height: "400px", width: "400px" }}
      >
        <ModifyItem />
      </Modal>
    </div>
  );
}

export default Repair;
